package logic

import (
	"context"
	"github.com/eeppee_admin/clouddisk/service/model"
	"github.com/eeppee_admin/clouddisk/service/helper"
	"github.com/eeppee_admin/clouddisk/service/internal/svc"
	"github.com/eeppee_admin/clouddisk/service/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type FilePreUploadLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewFilePreUploadLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FilePreUploadLogic {
	return &FilePreUploadLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *FilePreUploadLogic) FilePreUpload(req *types.FilePreUploadRequest) (resp *types.FilePreUploadResponse, err error) {

	sp := new(model.StorePool)
	has, err := l.svcCtx.Engine.Where("hash = ?", req.Md5).Get(sp)
	if err != nil {
		return
	}

	resp = new(types.FilePreUploadResponse)
	if has {
		// 上传成功
		resp.Identity = sp.Identity
	} else {
		// 获取该文件的UploadID, Key, 用于分片上传
		key, uploadId, err := helper.CosInitPart(req.Ext)
		if err != nil {
			return nil, err
		}

		resp.Key = key
		resp.UploadId = uploadId
	}


	return
}
